package com.huiyeji.hui.controller;

import com.huiyeji.hui.auth.Authenticator;
import com.huiyeji.hui.auth.License;
import com.huiyeji.hui.entity.User;
import com.huiyeji.hui.entity.UserInfoEntity;
import com.huiyeji.hui.exception.HuiException;
import com.huiyeji.hui.service.ApplicationService;
import com.huiyeji.hui.utils.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author zhaoduo
 */
@Controller
public class LrController {

    private static final Log logger = LogFactory.getLog(LrController.class);

    private final Authenticator authenticator = Authenticator.getInstance();

    private final ApplicationService service;

    @Autowired
    public LrController(ApplicationService applicationService){
        this.service = applicationService;
    }


    @ResponseBody
    @PostMapping("/login")
    public HuiResponse<?> doLogin(@Validated(Login.class) UserInfoEntity userInfo,
                                  BindingResult bindingResult,
                                  HttpSession session){
        ValidateUtil.analyzeBindingResult(bindingResult);
        User user = service.getUserInfo(userInfo);
        if (user != null){
            authenticator.authorized(session,user,License.GENERAL);
            return HuiResponse.ok();
        }
        return HuiResponse.error();
    }

    @GetMapping("/getUserInfo")
    @ResponseBody
    public HuiResponse<?> getUserInfo(HttpSession session) throws CloneNotSupportedException {
        User user = authenticator.check(session, License.GENERAL);
        User resUser = service.getUserInfoSafely(user);
        return HuiResponse.ok(resUser);
    }

    @PostMapping("/register")
    @ResponseBody
    public HuiResponse<?> register(@Validated(Register.class) UserInfoEntity userInfo,
                                   BindingResult bindingResult){
        ValidateUtil.analyzeBindingResult(bindingResult);
        if (!userInfo.getPassword().equals(userInfo.getConfirmPwd())){
            throw new HuiException("密码与确认密码不符");
        }
        service.register(userInfo);
        return HuiResponse.ok(SuccessEnum.REGISTER_SUCCESS);
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/lr.html";
    }

}
